package com.mll.snake.slice;

import com.mll.snake.ResourceTable;
import com.mll.snake.views.SnakeComponent;
import com.mll.snake.utils.Direction;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.IAbilityContinuation;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.IntentParams;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.window.service.WindowManager;
import ohos.distributedschedule.interwork.DeviceInfo;
import ohos.distributedschedule.interwork.DeviceManager;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.global.resource.NotExistException;
import ohos.global.resource.RawFileDescriptor;
import ohos.global.resource.Resource;
import ohos.media.common.Source;
import ohos.media.player.Player;
import ohos.multimodalinput.event.MmiPoint;
import ohos.multimodalinput.event.TouchEvent;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_CONTENT;
import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_PARENT;

public class EndlessAbilitySlice extends AbilitySlice  implements IAbilityContinuation {
    private DirectionalLayout myLayout = new DirectionalLayout(this);
    private DirectionalLayout inLayout = new DirectionalLayout(this);
    private SnakeComponent snakeComponent;
    private MyEventHandler handler;
    private boolean flag;
    private final int CLICK_START = 1;
    private final int CLICK_STOP = 2;
    private final int CLICK_BACK = 3;
    private final int CLICK_TRANSFORM = 4;
    private final int GAME_ROCKER = 5;
    private Button btnStart;
    private Button btnStop;
    private Button backBtn;
    private Button btnTransform;
    private Text text;
    private int score = 0;
    private float startX, startY, distanceX, distanceY;//滑动相关属性
    private int rote = 1000;//初始速度
    private int i = 1;
    private DirectionalLayout layoutTop = new DirectionalLayout(this);
    private DependentLayout rokerLayout = new DependentLayout(this);
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        DirectionalLayout.LayoutConfig config = new DirectionalLayout.LayoutConfig(MATCH_PARENT, MATCH_PARENT);
        config.setMargins(0, 0, 0, 0);
        myLayout.setWidth(MATCH_PARENT);
        myLayout.setHeight(MATCH_PARENT);
        myLayout.setOrientation(Component.VERTICAL);
        inLayout.setWidth(MATCH_PARENT);
        inLayout.setHeight(MATCH_CONTENT);
        inLayout.setOrientation(Component.VERTICAL);

        findViews();

        snakeComponent = new SnakeComponent(this);
        //设置按钮布局
        drawButtons();//画按钮
        clickListener();//点击事件
        snakeOnTouchEvent();//滑动事件
        EventRunner eventRunner = EventRunner.current();
        //事件处理实现类
        handler = new MyEventHandler(eventRunner);
        snakeComponent.setLayoutConfig(config);
        snakeComponent.setWidth(MATCH_PARENT);
        snakeComponent.setHeight(MATCH_PARENT);
        WindowManager.getInstance().getTopWindow().get().setStatusBarVisibility(Component.INVISIBLE);
        WindowManager.getInstance().getTopWindow().get().addFlags(WindowManager.LayoutConfig.MARK_ALLOW_EXTEND_LAYOUT);

        super.setUIContent(myLayout);

        try {
            Player mediaPlayer = new Player(this);
            RawFileDescriptor filDescriptor = getResourceManager().getRawFileEntry("entry/resources/base/media/bgm.mp3").openRawFileDescriptor();
            Source source = new Source(filDescriptor.getFileDescriptor(),
                    filDescriptor.getStartPosition(), filDescriptor.getFileSize());
            mediaPlayer.setSource(source);
            mediaPlayer.enableSingleLooping(true);//单曲循环
            mediaPlayer.prepare();
            mediaPlayer.play();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void findViews() {
        btnStart = new Button(this);
        btnStop = new Button(this);
        backBtn = new Button(this);
        btnTransform = new Button(this);
        text = new Text(this);
    }

    private void clickListener() {
        MyListener listener = new MyListener();
        btnStart.setClickedListener(listener);
        btnStop.setClickedListener(listener);
        backBtn.setClickedListener(listener);
        btnTransform.setClickedListener(listener);
        btnStart.setId(CLICK_START);
        btnStop.setId(CLICK_STOP);
        backBtn.setId(CLICK_BACK);
        btnTransform.setId(CLICK_TRANSFORM);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }



    class MyListener implements Component.ClickedListener {

        @Override
        public void onClick(Component component) {
            switch (component.getId()) {
                case CLICK_TRANSFORM:
                    //数据流转
                    if(getAvailableDeviceIds()!=null){
                        continueAbility(getAvailableDeviceIds().get(0));
                    }
                    System.out.println("没有"+getAvailableDeviceIds());
                    break;
                case CLICK_START:
                    flag = true;
                    new Thread() {
                        @Override
                        public void run() {
                            while (flag) {
                                try {
                                    //给当前线程加锁
                                    Thread.sleep(rote);
                                    score = snakeComponent.getmSnakeList().size() - 2;
                                    handler.sendEvent(1);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }.start();
                    break;
                case CLICK_STOP:
                    flag = false;
                    System.out.println("结束");
                    break;
                case CLICK_BACK:
                    flag = false;
                    //返回主页面
                    Intent intent = new Intent();
                    Operation operation1 = new Intent.OperationBuilder().withDeviceId("").withBundleName("com.mll.snake").withAbilityName("com.mll.snake.MainAbility").build();
                    intent.setOperation(operation1);
                    startAbility(intent);
            }
        }
    }

    class MyEventHandler extends EventHandler {

        public MyEventHandler(EventRunner runner) throws IllegalArgumentException {
            super(runner);
        }

        @Override
        protected void processEvent(InnerEvent event) {
            super.processEvent(event);
            if (event == null) {
                return;
            }
            int eventId = event.eventId;
            switch (eventId) {
                case 1:
                    if (snakeComponent != null) {
                        snakeComponent.invalidate();
                    }
                    if (score == i * 5) {//设置一个加速规则
                        rote = rote - 1 * 50;
                        i++;
                    }
                    text.setText("分数:" + score);
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 弧度转角度
     *
     * @param radian 弧度
     * @return 角度[0, 360)
     */
    private double radian2Angle(double radian) {
        double tmp = Math.round(radian / Math.PI * 180);
        return tmp >= 0 ? tmp : 360 + tmp;
    }

    /**
     * 滑动监听事件+方向摇杆监听
     *2022/1/12修改滑动监听事件
     * @return
     */
    public void snakeOnTouchEvent() {

        snakeComponent.setTouchEventListener(new Component.TouchEventListener() {
            @Override
            public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
                MmiPoint point = touchEvent.getPointerScreenPosition(0);
                // 两点在X轴的距离
                float lenX = (float) (point.getX() - snakeComponent.getViewCenterX());
                // 两点在Y轴距离
                float lenY = (float) (point.getY() - snakeComponent.getViewCenterY());
                // 两点距离
                float lenXY = (float) Math.sqrt((double) (lenX * lenX + lenY * lenY));
                // 计算弧度
                double radian = Math.acos(lenX / lenXY) * (point.getY() < snakeComponent.getViewCenterY() ? -1 : 1);
                // 计算角度
                double angle = radian2Angle(radian);

                System.out.println("++++++++++++++++++角度++++++++++++++++++=：" + angle);
                if(touchEvent.getAction() == TouchEvent.PRIMARY_POINT_UP){
                    snakeComponent.restorePosition();
                }
                else{
                    snakeComponent.handleEvent(touchEvent);
                }
                // 回调 返回参数
                snakeComponent.setmSnakeDirection(angle);
//                callBack(angle);

//                MmiPoint point = touchEvent.getPointerScreenPosition(0);
//                switch (touchEvent.getAction()) {
//                    case TouchEvent.OTHER_POINT_UP:
//                        startX = point.getX();
//                        startY = point.getY();
//                        break;
//                    case TouchEvent.PRIMARY_POINT_UP:
//                        distanceX = point.getX() - startX;
//                        distanceY = point.getY() - startY;
//                        break;
//                }
//                if (snakeComponent != null) {
//                    if (Math.abs(distanceX) > Math.abs(distanceY)) {
//                        if (distanceX > 200 && snakeComponent.getmSnakeDirection() != 3) {
//                            //右移
//                            snakeComponent.setmSnakeDirection(4);
//                        } else if (distanceX < -200 && snakeComponent.getmSnakeDirection() != 4) {
//                            //左移
//                            snakeComponent.setmSnakeDirection(3);
//                        }
//                    } else if (Math.abs(distanceX) < Math.abs(distanceY)) {
//                        if (distanceY > 200 && snakeComponent.getmSnakeDirection() != 1) {
//                            //下移
//                            snakeComponent.setmSnakeDirection(2);
//                        } else if (distanceY < -200 && snakeComponent.getmSnakeDirection() != 2) {
//                            //上移
//                            snakeComponent.setmSnakeDirection(1);
//                        }
//                    }
//                }
                return true;
            }
        });
    }

    /**
     * 摇杆支持几个方向
     */
    public enum DirectionMode {
        DIRECTION_2_HORIZONTAL,// 横向 左右两个方向
        DIRECTION_2_VERTICAL, // 纵向 上下两个方向
        DIRECTION_4_ROTATE_0, // 四个方向
        DIRECTION_4_ROTATE_45, // 四个方向 旋转45度
        DIRECTION_8 // 八个方向
    }

    /**
     * 方向
     */
    public enum MyDirection {
        DIRECTION_LEFT, // 左
        DIRECTION_RIGHT, // 右
        DIRECTION_UP, // 上
        DIRECTION_DOWN, // 下
        DIRECTION_UP_LEFT, // 左上
        DIRECTION_UP_RIGHT, // 右上
        DIRECTION_DOWN_LEFT, // 左下
        DIRECTION_DOWN_RIGHT, // 右下
        DIRECTION_CENTER // 中间
    }

    /**
     * 回调
     * 返回参数
     *
     * @param angle 摇动角度
     */
    private void callBack(double angle) {
        if (Direction.ANGLE_0 <= angle && Direction.ANGLE_8D_OF_0P > angle || Direction.ANGLE_8D_OF_7P <= angle && Direction.ANGLE_360 > angle) {
            // 右
            snakeComponent.setmSnakeDirection(4);
        } else if (Direction.ANGLE_8D_OF_0P <= angle && Direction.ANGLE_8D_OF_1P > angle) {
            // 右下
        } else if (Direction.ANGLE_8D_OF_1P <= angle && Direction.ANGLE_8D_OF_2P > angle) {
            // 下
            snakeComponent.setmSnakeDirection(2);
        } else if (Direction.ANGLE_8D_OF_2P <= angle && Direction.ANGLE_8D_OF_3P > angle) {
            // 左下
        } else if (Direction.ANGLE_8D_OF_3P <= angle && Direction.ANGLE_8D_OF_4P > angle) {
            // 左
            snakeComponent.setmSnakeDirection(3);
        } else if (Direction.ANGLE_8D_OF_4P <= angle && Direction.ANGLE_8D_OF_5P > angle) {
            // 左上
        } else if (Direction.ANGLE_8D_OF_5P <= angle && Direction.ANGLE_8D_OF_6P > angle) {
            // 上
            snakeComponent.setmSnakeDirection(1);
        } else if (Direction.ANGLE_8D_OF_6P <= angle && Direction.ANGLE_8D_OF_7P > angle) {
            // 右上
        }
    }



    /**
     * 滑动监听事件
     *  2022/1/12修改完滑动监听事件
     */
    //int getAction();//获取滑动方向PRIMARY_POINT_DOWN、PRIMARY_POINT_UP、POINT_MOVE、OTHER_POINT_DOWN或OTHER_POINT_UP。

    /**
     * 画按钮
     */
    public void drawButtons() {
        ShapeElement background0 = new ShapeElement();
        PixelMapElement btnBg = null;
        try {
            Resource bgResource =getResourceManager().getResource(ResourceTable.Media_game_text);
            btnBg = new PixelMapElement(bgResource);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotExistException e) {
            e.printStackTrace();
        }
        background0.setCornerRadius(120);
        Color color = new Color(Color.rgb(255,172,26));

        text.setText("分数:0");
        text.setTextSize(55);
        text.setMarginLeft(0);
        text.setMarginTop(20);
        text.setTextColor(color);
        text.setWidth(600);
        text.setHeight(90);
        text.setPaddingLeft(45);
        text.setBackground(btnBg);

        btnStart.setText("开始");
        btnStart.setTextSize(55);
        btnStart.setWidth(400);
        btnStart.setHeight(90);
        btnStart.setMarginTop(20);
        btnStart.setTextColor(color);
        btnStart.setBackground(btnBg);

        btnStop.setText("暂停");
        btnStop.setWidth(400);
        btnStop.setTextSize(55);
        btnStop.setMarginTop(20);
        btnStop.setHeight(90);
        btnStop.setTextColor(color);
        btnStop.setBackground(btnBg);



        backBtn.setText("返回");
        backBtn.setTextSize(55);
        backBtn.setWidth(400);
        backBtn.setMarginTop(20);
        backBtn.setHeight(90);
        backBtn.setTextColor(color);
        backBtn.setBackground(btnBg);

        btnTransform.setText("流转");
        btnTransform.setTextSize(55);
        btnTransform.setMarginTop(20);
        btnTransform.setWidth(420);
        btnTransform.setHeight(90);
        btnTransform.setTextColor(color);
        btnTransform.setBackground(btnBg);


        btnStart.setId(CLICK_START);
        btnStop.setId(CLICK_STOP);
        backBtn.setId(CLICK_BACK);

        layoutTop.setWidth(MATCH_PARENT);
        layoutTop.setHeight(MATCH_CONTENT);
        layoutTop.setOrientation(Component.HORIZONTAL);

        layoutTop.addComponent(text);
        layoutTop.addComponent(btnStart);
        layoutTop.addComponent(btnStop);
        layoutTop.addComponent(backBtn);
        layoutTop.addComponent(btnTransform);



        myLayout.addComponent(layoutTop);
        inLayout.addComponent(snakeComponent);
        myLayout.addComponent(inLayout);


    }
    /**
     * 获得所有已经连接的所有设备ID
     * @return 设备ID列表
     */
    public static List<String> getAvailableDeviceIds() {
        // 获得DeviceInfo列表，包含了已经连接的所有设备信息
        List<DeviceInfo> deviceInfoList = DeviceManager.getDeviceList(DeviceInfo.FLAG_GET_ONLINE_DEVICE);
        // 如果DeviceInfo列表为空则返回
        if (deviceInfoList == null || deviceInfoList.size() == 0) {
            System.out.println("没有当前设备");
            return null;
        }
        // 遍历DeviceInfo列表，获得所有的设备ID
        List<String> deviceIds = new ArrayList<>();
        for (DeviceInfo deviceInfo : deviceInfoList) {
            deviceIds.add(deviceInfo.getDeviceId());
        }
        // 返回所有的设备ID
        return deviceIds;
    }
    @Override
    public boolean onStartContinuation() {
        return true;
    }

    @Override
    public boolean onSaveData(IntentParams intentParams) {

//        intentParams.setParam("score",text.getText().toString());
//        intentParams.setParam("component",snakeComponent);
        return true;
    }

    @Override
    public boolean onRestoreData(IntentParams intentParams) {

//        String str = (String) intentParams.getParam("score");
//        text.setText(str);
//        SnakeComponent component = (SnakeComponent) intentParams.getParam("component");
//        snakeComponent = component;
        return true;
    }

    @Override
    public void onCompleteContinuation(int i) {
        terminateAbility();
    }

}
